package com.example.demo;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
//import com.example.demo.utils.PushMessUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@RunWith(SpringRunner.class)
@SpringBootTest
public class SendMsgWechatApp {
    private String appId= "";
    private String secret="";
//    @Value("${wx.templateId}")
    private String templateId="xZOeGp9Lr23QmBDvZYWibKuJpjL_lEnFFoyWQa4gys4";
    private String templateIdReceive="5Rwk_UdYM0SWC74XDooREILc5z9SZ0aoLZLlbXekaBc";
//    @Value("${wx.openid}")
    private String openid="olu7R4j_vyn8Q6rzwUxDdpLgk9zQ";
//    private String openid;
    private String code="0538UE1w3CI1d03dm30w3ZzCko18UE1u";
//    private static RestTemplate restTemplate;
//    @Autowired
//    private ObjectMapper objectMapper;
    @Test
    public void sendMsg() throws JsonProcessingException {
        //1:获取token(接口调用凭证)
//        String token = queryToken();
//        code2Session();
        //2:发送订阅消息
        String token="66_RNKUKeLC4xy7SOeZ0RSjoMyeic3FfB3brJhRM-PzcX6DffKghYVPbtId7J9_VZ56m-NcWDOGDyR38aWc30IZm_Und1T55nCrhQ3k_zSu7wnsvOwJ0O6TfKHfQXYJAUjAFAARL";
        sendRejectOrder(token);
        sendReceiveOrder(token);
    }
    /*获取openid和session_key，参数code是小程序端传过来的*/
    public Map code2Session() throws JsonMappingException, JsonProcessingException {
        String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        Map<String, Object> params = new HashMap();
        params.put("appId", appId);
        params.put("appSecret", secret);
        params.put("code", code);
        ResponseEntity<String> response = getInstance("utf-8").exchange(CODE2SESSION_URL, HttpMethod.GET, RequestEntity.EMPTY, String.class, params);
        JsonNode json = objectMapperInstance().readTree(response.getBody());
        Map returnMap=new HashMap();
        returnMap.put("session_key",json.get("session_key").asText());
        /*获取到openid*/
        returnMap.put("openid",json.get("openid").asText());
        this.openid = json.get("openid").asText();
        return returnMap;
    }

    @Test
    public void queryToken(){
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        tokenUrl = tokenUrl+"&appid="+appId+"&secret="+secret;
        String result = HttpUtil.get(tokenUrl);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String token = jsonObject.get("access_token").toString();
        System.out.println(token);
//        return token;
    }

    public void sendRejectOrder(String token){
        String msgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
        msgUrl = msgUrl+"?access_token="+token;
        //设置模板参数
        HashMap<String,Object> paramMap = new HashMap<>();
        paramMap.put("touser",openid);
        paramMap.put("template_id",templateId);
//        paramMap.put("page","pages/main/main");
        paramMap.put("page","pages/main/main");
        //设置data模板内容
        HashMap<String,Object> data = new HashMap<>();
        data.put("thing1",formatParam("报修已被拒绝"));
        data.put("thing2",formatParam("张三"));
        data.put("thing3",formatParam("距离太远"));
        data.put("thing5",formatParam("拒绝报修"));
        paramMap.put("data",data);
        //转json字符串
        String jsonObject = JSONUtil.toJsonStr(paramMap);
        String result = HttpUtil.post(msgUrl,jsonObject);
        System.out.println(result);
    }
    public void sendReceiveOrder(String token){
        String msgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
        msgUrl = msgUrl+"?access_token="+token;
        //设置模板参数
        HashMap<String,Object> paramMap = new HashMap<>();
        paramMap.put("touser",openid);
        paramMap.put("template_id",templateIdReceive);
//        paramMap.put("page","pages/main/main");
        paramMap.put("page","pages/main/main");
        //设置data模板内容
        HashMap<String,Object> data = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time7 = sdf.format(new Date());
        data.put("thing6",formatParam("李四"));
        data.put("time7",formatParam(time7));
        paramMap.put("data",data);
        //转json字符串
        String jsonObject = JSONUtil.toJsonStr(paramMap);
        String result = HttpUtil.post(msgUrl,jsonObject);
        System.out.println(result);
    }
    public HashMap<String,Object> formatParam(String value){
        HashMap<String,Object> data = new HashMap<>();
        data.put("value",value);
        return data;
    }

    public static RestTemplate getInstance(String charset) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName(charset)));
        return restTemplate;
    }
    public static ObjectMapper objectMapperInstance(){
        return new ObjectMapper();
    }


    @Test
    public void getAccessToken(){
//        PushMessWechatAppUtil accessTokenUtils = new PushMessWechatAppUtil();
//        String token = accessTokenUtils.PushMessWechatAppUtil();
//        System.out.println(token);
    }
}

